package com.easylinkin.linkappapi.openapi.service.impl;

import com.easylinkin.linkappapi.alarm.entity.AlarmTemplate;
import com.easylinkin.linkappapi.alarm.mapper.AlarmTemplateMapper;
import com.easylinkin.linkappapi.alarm.service.AlarmTemplateService;
import com.easylinkin.linkappapi.openapi.service.ApplicationCopyDirectService;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @program: linkapp-group-cloud
 * @description: 告警模板复制
 * @author: chenkaixuan
 * @create: 2021-09-07 10:47
 */
@Slf4j
@Order(1)
@Service
public class ApplicationCopyAlarmModelDirectServiceImpl implements ApplicationCopyDirectService {
    @Resource
    AlarmTemplateMapper alarmTemplateMapper;


    @Override
    public RestMessage copy(HashMap<String, String> screenmap, HashMap<String, String> map, LinkappUser newLinkappUser, LinkappUser oldLinkappUser) {
        return null;
    }

    @Override
    public RestMessage copy(LinkappUser newLinkappUser, LinkappUser oldLinkappUser) {
        if (newLinkappUser == null || oldLinkappUser == null) {
            return RestBuilders.failureMessage().setMessage("用户为空");
        }
        RestMessage restMessage = RestBuilders.successBuilder().build();
        AlarmTemplate alarmTemplate = new AlarmTemplate();
        alarmTemplate.setTenantId(oldLinkappUser.getTenantId());
        List<AlarmTemplate> alarmTemplates = alarmTemplateMapper.getAlarmTemplates(alarmTemplate, oldLinkappUser.getId() + "");
        if (alarmTemplates == null || alarmTemplates.size() <= 0) {
            return restMessage;
        }
        Date date = new Date();
        alarmTemplates = alarmTemplates.stream().map(m -> {
            m.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            m.setCreateTime(date);
            m.setModifyTime(date);
            m.setTenantId(newLinkappUser.getTenantId());
            m.setUserId(newLinkappUser.getId() + "");
            return m;
        }).collect(Collectors.toList());
        //批量新增
        int batchSize = 100;
        if (alarmTemplates != null && alarmTemplates.size() > 0) {
            for (int idx = 0; idx < alarmTemplates.size(); idx += batchSize) {
                List<AlarmTemplate> list = alarmTemplates.subList(idx, Math.min(alarmTemplates.size(), idx + batchSize));
                alarmTemplateMapper.batchInsert(list);
            }
        }
        log.info("告警模板拷贝完成");
        return restMessage;
    }
}
